<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Object-oriented programming</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="PHP, learn PHP, OOP, object oriented programming, programming, language">
<meta name="description" content="In this part of the PHP tutorial, we cover Object-oriented programming.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Object-oriented programming</h1>

<p>
In this part of the PHP tutorial, we will talk about object oriented programming in PHP.
</p>

<p>
There are three widely used programming paradigms there. Procedural programming, 
functional programming and object-oriented programming. PHP 5 supports both 
procedural and object-oriented programming. Earlier 
versions of PHP had limited or no support for OOP. 
</p>

<div class="center">
<script type="text/javascript"><!--
google_ad_client = "ca-pub-9706709751191532";
/* top_horizontal */
google_ad_slot = "3327173442";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<p>
<b>Object-oriented programming (OOP)</b> is a programming paradigm that uses objects
and their interactions to design applications and computer programs. (Wikipedia)
</p>

<p>
There are some basic programming concepts in OOP:
</p>

<ul>
    <li>Abstraction</li>
    <li>Polymorphism</li>
    <li>Encapsulation</li>
    <li>Inheritance</li>
</ul>

<p>
The <b>abstraction</b> is simplifying complex reality by modeling classes appropriate to the problem. 
The <b>polymorphism</b> is the process of using an operator or function in different ways for different data input. 
The <b>encapsulation</b> hides the implementation details of a class from other objects.
The <b>inheritance</b> is a way to form new classes  using classes that have already been defined.
</p>

<h2>Objects</h2>

<p>
Objects are basic building blocks of a PHP OOP program. An object is a combination of data and methods.
In a OOP program, we create objects. These objects communicate together through methods. Each object 
can receive messages, send messages and process data. 
</p>

<p>
There are two steps in creating an object. First, we create a class. A <b>class</b> is a template for an object. 
It is a blueprint, which describes the state and behavior that the objects of the class all share. A class
can be used to create many objects. Objects created at runtime from a class are called <b>instances</b> of that 
particular class. 
</p>

<pre class="code">
&lt;?php

class Simple {}

$object = new Simple();
print_r($object);
echo gettype($object), "\n";

?&gt;
</pre>

<p>
In our first example, we create a simple object. 
</p>

<pre class="explanation">
class Simple {}
</pre>

<p>
This is a simple class definition. The body of the template is empty. It does not
have any data or methods. 
</p>

<pre class="explanation">
$object = new Simple();
</pre>

<p>
We create a new instance of the Simple class. For this we have the <code>new</code>
keyword. The <b>$object</b> variable is the handle to the created object. 
</p>

<pre class="explanation">
print_r($object);
echo gettype($object), "\n";
</pre>

<p>
We use the <code>print_r()</code> function to get information about the object and
the <code>gettype()</code> function, to get the type of the variable. 
</p>

<pre>
$ php class.php 
Simple Object
(
)
object
</pre>

<p>
We don't get much info, since the class definition was empty. 
The type of the variable is <code>object</code>.
</p>

<h2>Object attributes</h2>

<p>
Object attributes is the data bundled in an instance of a class. The 
object attributes are called <b>instance variables</b> or <b>member fields</b>.
An instance variable is a variable defined in a class, for which each object
in the class has a separate copy.
</p>

<pre class="code">
&lt;?php

class Person {

    public $name = "";
}

$p1 = new Person();
$p1->name = "Jane";

$p2 = new Person();
$p2->name = "Beky";

echo $p1->name . "\n"; 
echo $p2->name . "\n"; 

?&gt;
</pre>

<p>
In the above PHP script, we have a Person class with
one member field. 
</p>

<pre class="explanation">
$p1 = new Person();
$p1->name = "Jane";
</pre>

<p>
We create an instance of the Person class. And set the
$name variable to "Jane". We use the <b>-></b> operator to 
access the attributes of objects. 
</p>

<pre class="explanation">
$p2 = new Person();
$p2->name = "Beky";
</pre>

<p>
We create another instance of the Person class. Here
we set the variable to "Beky".
</p>

<pre class="explanation">
echo $p1->name . "\n"; 
echo $p2->name . "\n"; 
</pre>

<p>
We print the contents of the variables to the console. 
</p>

<pre>
$ php memberfields.php 
Jane
Beky
</pre>

<p>
We see the output of the script. Each instance of the Person class has a separate
copy of the $name member field. 
</p>

<h2>Methods</h2>

<p>
Methods are functions defined inside the body of a class. They are used to perform operations 
with the attributes of our objects. Methods are essential in <b>encapsulation</b> concept of 
the OOP paradigm. For example, we might have a connect() method in our AccessDatabase class. 
We need not to be informed, how exactly the method connect() connects to the database. 
We only know, that it is used to connect to a database. This is essential in dividing
responsibilities in programming. Especially in large applications. 
</p>

<pre class="code">
&lt;?php

class Circle {

    public $radius;

    function setRadius($radius) {
        $this->radius = $radius;
    }

    function area() {
        return $this->radius * $this->radius * M_PI;
    }
}

$c = new Circle();
$c->setRadius(5);

echo $c->area(), "\n";

?&gt;
</pre>

<p>
In the code example, we have a Circle class. We define two methods.
</p>

<pre class="explanation">
 public $radius;
</pre>

<p>
We have one member field. It is the radius of the circle. The <code>public</code>
keyword is an access specifier. It tells that the variable is fully accessible from the outside
world. 
</p>

<pre class="explanation">
function setRadius($radius) {
    $this->radius = $radius;
}
</pre>

<p>
This is the setRadius() method. It is a normal PHP function. 
We call functions defined inside classes <b>methods</b>.
The <code>$this</code> variable is a special variable, which
we use to access the member fields from methods. 
</p>

<pre class="explanation">
function area() {
    return $this->radius * $this->radius * M_PI;
}
</pre>

<p>
The area() method returns the area of a circle. The <code>M_PI</code> is 
a built-in constant. 
</p>

<pre>
$ php circle.php 
78.5398163397
</pre>

<p>
Running the example. 
</p>

<h2>Access modifiers</h2>

<p>
<b>Access modifiers</b> set the visibility of methods and member fields. PHP 5 has three access modifiers.
<code>public</code>, <code>protected</code> and <code>private</code>.
<code>public</code> members can be accessed from anywhere. <code>protected</code> 
members can be accessed only within the class itself and by inherited and parent classes. 
<code>private</code> members may only be accessed by the class that defines the member.
</p>

<p>
Access modifiers protect data against accidental modifications. They make the programs more robust.
</p>

<pre class="code">
&lt;?php

class Person {

    public $name = "";
    private $age;
}

$p = new Person();
$p->name = "Jane";
#$p->age = 17;

echo $p->name . "\n";

?&gt;
</pre>

<p>
In the above PHP script, we have two member fields. One is declared public, the other private. 
</p>

<pre class="explanation">
$p->name = "Jane";
#$p->age = 17;
</pre>

<p>
We access the $name member from the outside world. By the outside world, we mean 'not in the class'.
It is OK, since the $name variable is declared <code>public</code>.
Accessing the $age member is not possible. The <code>private</code> modifier prohibits this.
If we uncomment the code line, we will get the 'Fatal error: Cannot access private property Person::$age'
error.
</p>

<pre class="code">
&lt;?php

class Base {
    
    public $name = "Base";
    protected $id = 6124;
    private $is_defined = "yes"; 

}

class Derived extends Base {

    public function info() {
        echo "This is Derived class\n";
        echo "Members inherited: \n";

        echo $this->name . "\n";
        echo $this->id . "\n";
        echo $this->is_defined . "\n";
    }
}

$derived = new Derived();
$derived->info();

?&gt;
</pre>

<p>
In this PHP script, we have a Derived class, which extends the Base class. The
Base class has three member fields. All with different access modifiers. 
The $is_defined member is not inherited. The <code>private</code>
modifier prevents this.
</p>

<pre class="explanation">
public function info() {
</pre>

<p>
The info() method has a <code>public</code> access modifier. 
This means, it can be called outside the class environment. 
</p>

<pre>
$ php access.php 
This is Derived class
Members inherited: 
Base
6124

$
</pre>

<p>
Running the PHP script, we receive this output. The public and protected members are inherited, the 
private member is not. 
</p>

<pre class="code">
&lt;?php

class SysInfo {

    private function get_date() {
        return date("Y/m/d");
    }

    private function get_version() {
        return phpversion();
    }

    public function getInfo() {

        $date = $this->get_date();
        $version = $this->get_version();

        echo "The date is: $date\n";
        echo "The PHP version is: $version\n";
    }
}

$sys = new SysInfo();
$sys->getInfo();
#$sys->get_date();

?&gt;
</pre>

<p>
In this PHP script, we have a SysInfo class. It outputs some
system information to the console. We have two private functions and 
one public. The private methods are here only for internal working of
the SysInfo class. They are not meant to be called outside the class. 
</p>

<pre class="explanation">
$sys = new SysInfo();
$sys->getInfo();
#$sys->get_date();
</pre>

<p>
We create an instance of the SysInfo class and call the publicly available
getInfo() method. The getInfo() method uses internally the private methods to
do its job. Uncommenting the last code line yields to error.
</p>

<h2>Method overloading</h2>

<p>
<b>Method overloading</b> allows the creation of several methods with the same name 
which differ from each other in the type of the input.
</p>

<p>
What is method overloading good for? The Qt4 library gives a nice example for the usage. 
The QPainter class has three methods to draw a rectangle. Their name is drawRect() and their
parameters differ. One takes a reference to a floating point rectangle object, another takes
a reference to an integer rectangle object and the last one takes four parameters, x, y, width, height.
If the C++ language, which is the language in which Qt is developed, didn't have method overloading, the
creators of the library would have to name the methods like drawRectRectF(), drawRectRect(), drawRectXYWH().
The solution with method overloading is more elegant. 
</p>

<pre class="code">
&lt;?php

class Sum {

    public function getSum() {
        return 0;
    }

    public function getSum($x) {
        return $x;
    }

    public function getSum($x, $y) {
        return $x + $y;
    }
}

$s = new Sum();
echo $s->getSum() . "\n" ;
echo $s->getSum(5) . "\n" ;
echo $s->getSum(3, 4) . "\n" ;

?&gt;
</pre>

<p>
This is a method overloading, we know from languages like C#, Java or C++. But this
does not work in PHP. Running this example, we get the following error: 'Fatal error: Cannot redeclare Sum::getSum()'.
PHP functions can take arbitrary number of variables by default. 
</p>

<p>
To simulate method overloading in PHP, we use the <code>func_get_args()</code> function. 
</p>

<pre class="code">
&lt;?php

class Sum {

    public function getSum() {
        $args = func_get_args();

        if (empty($args)) return 0;

        foreach ($args as $arg) {
            $sum += $arg;
        }

        return $sum;
    }
}

$s = new Sum();
echo $s->getSum() . "\n" ;
echo $s->getSum(5) . "\n" ;
echo $s->getSum(3, 4) . "\n" ;
echo $s->getSum(3, 4, 7) . "\n" ;

?&gt;
</pre>

<p>
This time, the script will run. 
</p>

<pre class="explanation">
$args = func_get_args();
</pre>

<p>
The <code>func_get_args()</code> function returns an array 
comprising a function's argument list. 
</p>

<pre class="explanation">
foreach ($args as $arg) {
    $sum += $arg;
}
</pre>

<p>
We go throught all members of the array, and calculate the sum.
</p>

<pre class="explanation">
echo $s->getSum() . "\n" ;
echo $s->getSum(5) . "\n" ;
echo $s->getSum(3, 4) . "\n" ;
echo $s->getSum(3, 4, 7) . "\n" ;
</pre>

<p>
We call the same method name with different number of 
inputs. 
</p>


<h2>The constructor</h2>

<p>
A constructor is a special kind of a method. It is automatically called, when the object is created. 
The purpose of the constructor is to initiate the state of the object. 
The name of the constructor in PHP 5 is always <code>__construct()</code>. (Two underscores)
</p>

<pre class="code">
&lt;?php

class Song {

    function __construct() {
        echo "Song object is created \n";
    }
}

$song = new Song();

?&gt;
</pre>

<p>
We have a Song class. This class has a constructor, that prints message to the console. 
</p>

<pre class="explanation">
$song = new Song();
</pre>

<p>
This is the time, when the object is created and the constructor is called.
We get a message in the console. 
</p>

<pre>
$ php constructor.php 
Song object is created 
</pre>

<p>
This is the output of the script. 
</p>

<p>
Constructors often take arguments. 
</p>

<pre class="code">
&lt;?php

class Song {

    function __construct($song) {
        echo "Song $song is created \n";
    }
}

$song = new Song("Bad romance");

?&gt;
</pre>

<p>
We modify the previous example a bit. We pass a value to the constructor. 
</p>

<pre class="explanation">
function __construct($song) {
    echo "Song $song is created \n";
}
</pre>

<p>
The passed argument is stored in the local <b>$song</b> variable. 
</p>

<pre>
$ php constructor2.php 
Song Bad romance is created 
</pre>

<p>
Now we have a message with a song title printed to the console. 
</p>

<p>
In the next example, we initiate data members of the class.
Initiation of variables is a typical job for constructors. 
</p>

<pre class="code">
&lt;?php

class Friend {

    private $born;
    private $name;

    function __construct($name, $born) {
        $this->name = $name;
        $this->born = $born;
    }

    function getInfo() {
        echo "My Friend $this->name was born in $this->born\n";
    }
}

$friend = new Friend("Lenka", 1990);
$friend->getInfo();

?&gt;
</pre>

<p>
We have a Friend class with data members and methods. 
</p>

<pre class="explanation">
private $born;
private $name;
</pre>

<p>
We have two variables in the class definition. The <code>private</code> keyword is
an access modifier. It is a form of encapsulation. The <code>private</code> keyword
is the most restrictive modifier. It allows only the object in question to access the variable. 
No descendants, no other objects. More about this topic later. 
</p>

<pre class="explanation">
function __construct($name, $born) {
    $this->name = $name;
    $this->born = $born;
}
</pre>

<p>
In the constructor, we initiate the two data members. The <code>$this</code> variable
is a handler used to reference the object variables. 
</p>

<pre class="explanation">
$friend = new Friend("Lenka", 1990);
$friend->getInfo();
</pre>

<p>
We create a Friend object with two arguments. Then we call the <b>getInfo()</b> method
of the object. To call object methods, we use the -> operator. 
</p>

<pre>
$ php friend.php 
My Friend Lenka was born in 1990
</pre>


<h2>Class constants</h2>

<p>
PHP enables to create class constants. These constants do not belong to a concrete object.
They belong to the class. By convention, constants are written in uppercase letters. 
</p>

<pre class="code">
&lt;?php

class Math {
    const PI = 3.14159265359;

    public function getPI() {
        echo self::PI;
    }
}

$math = new Math();

echo Math::PI, "\n";
echo $math->getPI(), "\n";

?&gt;
</pre>

<p>
We have a Math class with a PI constant. 
</p>

<pre class="explanation">
const PI = 3.14159265359;
</pre>

<p>
The <code>const</code> keyword is used to define a constant.
</p>

<pre class="explanation">
public function getPI() {
    echo self::PI;
}
</pre>

<p>
Class constants are accessed from within methods using the <code>self</code> keyword followed
by two colons. 
</p>

<pre class="explanation">
echo Math::PI, "\n";
echo $math->getPI(), "\n";
</pre>

<p>
We print the PI constant to the console. In the first case, we get the constant value
by referring to the class name, followed by two colons and a constant name. 
Note that no object was needed to get the class constant. 
In the second case, we use the object method. 
</p>


<h2>The instanceof keyword</h2>

<p>
The <code>instanceof</code> keyword is used to determine whether a
PHP variable is an instantiated object of a certain class.
</p>

<pre class="code">
&lt;?php

class Cat {}
class Dog {}
class Bird {}

$objects = array(new Cat(), new Dog(), new Cat(), 
                 new Bird(), new Bird(), new Dog(),
                 new Dog(), new Cat(), new Bird()
                 );

shuffle($objects);

foreach ($objects as $object) {

    if ($object instanceof Cat) {
        echo "It is a Cat\n";
    } elseif ($object instanceof Dog) {
        echo "It is a Dog\n";
    } else if ($object instanceof Bird) {
        echo "It is a Bird\n";
    }
}

?&gt;
</pre>

<p>
In the above script, we have three classes. Cat, Dog and Bird. 
We traverse the array and print the class for each array value.
</p>

<pre class="explanation">
$objects = array(new Cat(), new Dog(), new Cat(), 
                 new Bird(), new Bird(), new Dog(),
                 new Dog(), new Cat(), new Bird()
                 );
</pre>

<p>
We create an array of these objects. 
</p>

<pre class="explanation">
shuffle($objects);
</pre>

<p>
We shuffle the array. At this point, we don't know the class types
for the values of the array.
</p>

<pre class="explanation">
if ($object instanceof Cat) {
    echo "It is a Cat\n";
}
</pre>

<p>
Here we use the <code>instanceof</code> keyword to find out the
type of the class. 
</p>

<pre>
$ php instanceof.php 
It is a Bird
It is a Cat
It is a Cat
It is a Dog
It is a Dog
It is a Cat
It is a Dog
It is a Bird
It is a Bird
</pre>

<p>
You might get this output. 
</p>


<h2>The __toString() method</h2>

<p>
When we use the <code>print</code> or the <code>echo</code> keyword
with the object instance, the <code>__toString()</code> special method is called.
We will demonstrate this in the following example. 
</p>

<pre class="code">
&lt;?php

class Cat {

    public $name;
    public $age;


    function __construct($name, $age) {
        $this->age = $age;
        $this->name = $name;
    }

    function __toString() {
        return "Cat: $this->name, Age: $this->age \n";
    }

}

$missy = new Cat("Missy", 6);
$lucky = new Cat("Lucky", 4);

print $missy;
echo $lucky;

?&gt;
</pre>

<p>
We have a Cat class with a <code>__toString()</code> special method
defined. 
</p>

<pre class="explanation">
function __toString() {
    return "Cat: $this->name, Age: $this->age \n";
}
</pre>

<p>
The method prints the basic info about the object. 
</p>

<pre class="explanation">
$missy = new Cat("Missy", 6);
$lucky = new Cat("Lucky", 4);
</pre>

<p>
We create two objects of the Cat class. 
</p>

<pre class="explanation">
print $missy;
echo $lucky;
</pre>

<p>
And we use the <code>print</code> or the <code>echo</code> keywords
on them. 
</p>

<pre>
$ php tostring.php 
Cat: Missy, Age: 6 
Cat: Lucky, Age: 4 
</pre>

<p>
This is what we get, when we run the script. 
</p>


<h2>Inheritance</h2>

<p>
The inheritance is a way to form new classes using classes that have already been defined. 
The newly formed classes are called <b>derived</b> classes, the classes that we derive from
are called <b>base</b> classes. Important benefits of inheritance are code reuse and reduction 
of complexity of a program. The derived classes (descendants) override or extend the 
functionality of base classes (ancestors). 
</p>

<pre class="code">
&lt;?php

class Base {
    function __construct() {
       echo "Construction of Base class \n";
    }
}

class Derived extends Base {
    function __construct() {
        parent::__construct();
        echo "Construction of Derived class \n";
    }
}

$obj1 = new Base();
$obj2 = new Derived(); 

?&gt;
</pre>

<p>
In this PHP script, we have two classes. A Base class and a Derived class. 
The Derived class inherits from the Base class. 
</p>

<pre class="explanation">
class Derived extends Base {
</pre>

<p> 
In PHP, we use the <code>extends</code> keyword to create  
inheritance relations.
</p>

<pre class="explanation">
function __construct() {
    parent::__construct();
    echo "Construction of Derived class \n";
}
</pre>

<p>
In the constructor of the Derived class, we call the parent constructor. 
We use the <code>parent</code> keyword, followed by two colons
and the <code>__construct()</code> method. The constructors of the parent
classes must be called explicitly. 
</p>

<pre class="explanation">
$obj1 = new Base();
$obj2 = new Derived(); 
</pre>

<p>
We instantiate both the Base and the Derived classes.
</p>

<pre>
$ php derived.php 
Construction of Base class 
Construction of Base class 
Construction of Derived class 
</pre>

<p>
This is the output of the PHP script. 
</p>

<p>
A more complex example follows. 
</p>

<pre class="code">
&lt;?php

abstract class Being { 
    protected $isAlive = true;
   
    public function isAlive() {
        if ($this->isAlive) {
            echo "Being is alive\n";
        } else {
            echo "Being is not alive\n";
        }
    }

    public function kill() {
        $this->isAlive = false;
    }

}

abstract class Animal extends Being {

    protected $age;

    public function __construct($age) {
        $this->age = $age;
    }

    protected function setAge($age) {
        $this->age = $age;
    }

    public function getAge() {
        return $this->age;
    }
}

class Cat extends Animal {

    private $name;

    public function __construct($name, $age) {
        $this->name = $name;
        parent::__construct($age);
    }

    public function getName() {
        return $this->name;
    }
}

$cat = new Cat("Cici", 4);
$cat->isAlive();
echo $cat->getName() . " is " .  $cat->getAge() . " years old\n";
$cat->kill();
$cat->isAlive();

?&gt;
</pre>

<p>
We have used several new concepts here. In the code example, we have three classes. 
Being, Animal and Cat. The Animal class inherits from the Being class. The Cat class inherits
from the Animal class. Classes inherit methods and data members, that are not declared as private.
</p>

<pre class="explanation">
abstract class Being {
</pre>

<p>
The Being class is declared to be <code>abstract</code>.
The abstract keyword prohibits instantiation of classes.
It does not make much sense to create an instance of the class Being. 
</p>

<pre class="explanation">
protected $isAlive = true;
</pre>

<p>
The <b>$isAlive</b> data member is declared to be <code>protected</code>.
Such members can be accessed only by the classes, that define them and by their descendants.
</p>

<pre class="explanation">
abstract class Animal extends Being {
</pre>

<p>
The Animal class is also declared to be abstract. It inherits from class Being.
For this, we use the <code>extends</code> keyword. The Animal is descendant. It
inherits methods and variables of the base Being class.
</p>

<pre class="explanation">
class Cat extends Animal {
</pre>

<p>
The Cat class inherits from the Animal class. It inherits from the Animal class and
indirectly from the Being class too. It is not declared abstract, which means, we can instantiate
it. 
</p>

<pre class="explanation">
parent::__construct($age);
</pre>

<p>
In the constructor of the Cat class, we call the parent constructor
using the <code>parent</code> keyword, followed by two colons
and the <code>__construct()</code> method. The constructors of the parent
classes must be called explicitly. 
</p>

<pre class="explanation">
$cat = new Cat("Cici", 4);
$cat->isAlive();
echo $cat->getName() . " is " .  $cat->getAge() . " years old\n";
$cat->kill();
$cat->isAlive();
</pre>

<p>
We create a new Cat. Cici, 4 years old. Then we call functions on the cici object. 
Note the usage of methods, that were not created in the Cat class, but rather inherited
from the parent classes. 
</p>

<pre>
$ php inheritance.php 
Being is alive
Cici is 4 years old
Being is not alive
</pre>

<p>
Output of the script. 
</p>

<h2>Abstract classes and methods</h2>

<p>
PHP 5 introduces abstract classes and methods. Abstract classes cannot be instantiated. If a class
contains at least one abstract method, it must be declared abstract too. Abstract methods cannot be implemented,
they merely declare the methods' signatures. When we inherit from an abstract class, all abstract methods
must be implemented by the derived class. Furthermore, these methods must be declared with the same
of less restricted visibility. 
</p>

<p>
Unlike <b>interfaces</b>, abstract classes may have methods with full implementation and may also have
defined member fields. So abstract classes may provide a partial implementation. Programmers often put
some common functionality into abstract classes. And these abstract classes are later subclassed to 
provide more specific implementation. For example, the Qt graphics library has a QAbstractButton, which 
is the abstract base class of button widgets, providing functionality common to buttons. Buttons 
Q3Button, QCheckBox, QPushButton, QRadioButton, and QToolButton inherit from this base abstract class. 
</p>

<p>
Formally put, abstract classes are used to enforce a protocol. A protocol is a set of operations, 
which all implementing objects must support. 
</p>

<pre class="code">
&lt;?php

abstract class Drawing {
    protected $x = 0;
    protected $y = 0;

    public abstract function area();

    public function getCoordinates() {
        echo "\$x is $this->x\n";
        echo "\$y is $this->y\n";
    }
}

class Circle extends Drawing {
   
    private $radius;

    public function __construct($x, $y, $r) {
        $this->radius = $r;
        $this->x = $x;
        $this->y = $y;
    }

    public function area() {
        return $this->radius * $this->radius * pi();
    }

   public function __toString() {
       return "Circle, at x: $this->x, y: $this->y, radius: $this->radius";
   }

}

$o = new Circle(12, 45, 22);
echo "$o \n";
echo "Area of the circle: " . $o->area() . "\n";
echo $o->getCoordinates();

?&gt;
</pre>

<p>
In our PHP script, we have an abstract base Drawing class. 
The class defines two member fields, defines one method and declares one method. One of the methods
is abstract, the other one is fully implemented. The Drawing class
is abstract, because we cannot draw it. We can draw a circle, a dot or a square. 
The Drawing class has some common functionality to the objects, that
we can draw. 
</p>

<pre class="explanation">
class Circle extends Drawing {
</pre>

<p>
A Circle is a subclass of the Drawing class. It must implement the
abstract area method. 
</p>

<pre>
$ php abstract.php 
Circle, at x: 12, y: 45, radius: 22 
Area of the circle: 1520.53084434
$x is 12
$y is 45
</pre>

<p>
Output of the script. 
</p>


<h2>Interfaces</h2>

<p>
A remote control is an interface between the viewer and the TV. It is an interface to this electronic
device. Diplomatic protocol guides all activities in the diplomatic field. Rules of the road are rules
that motorists, cyclists and pedestrians must follow. Interfaces in programming are
analoguos to the previous examples. 
</p>

<p>
Interfaces are:
</p>

<ul>
<li>APIs</li>
<li>Contracts</li>
</ul>

<p>
Objects interact with the outside world with the methods, they expose. The actual implementation is not
important to the programmer, or it also might be secret. A company might sell a library and it does not
want to disclose the actual implementation. A programmer might call a maximize() method on a window
of a GUI toolkit, but knows nothing about how this method is implemented. From this point of view, 
interfaces are methods, through which objects interact with the outside world, without exposing too much
about their inner workings.
</p>

<p>
From the second point of view, interfaces are contracts. If agreed upon, they must be followed. They 
are used to design an architecture of an application. They help organize the code.  
</p>

<p>
Interfaces are fully abstract types. They are declared using the <code>interface</code> keyword. 
Interfaces can only have method signatures and constants. All method signatures declared in an interface must be public.
They cannot have fully implemented methods, nor 
member fields. A PHP class may implement any number of interfaces. An interface can also extend
any number of interfaces. A class that implements an interface must implement all method signatures of
an interface.  
</p>

<p>
Interfaces are used to simulate <b>multiple inheritance</b>. A PHP class can extend only one class. 
A PHP class can implement multiple interfaces. Multiple inheritance using the interfaces is not 
about inheriting methods and variables. It is about inheriting ideas or contracts, which are described
by the interfaces. 
</p>

<p>
There is one important distinction between interfaces and abstract classes. Abstract classes provide partial
implementation for classes, that are related in the inheritance hierarchy. Interfaces on the other hand can 
be implemented by classes, that are not related to each other. For example, we have two buttons.
A classic button and a round button. Both inherit from an abstract button class, that provides some
common functionality to all buttons. Implementing classes are related, since all are buttons. 
Another example might have classes Database and SignIn. They are not related to each other. We
can apply an ILoggable interface, that would force them to create a method to do logging. 
</p>

<pre class="code">
&lt;?php

interface IInfo {

    public function do_inform();
}

class Some implements IInfo {

    public function do_inform() {
        echo "This is a Some class\n";
    }
}

$sm = new Some();
$sm->do_inform();

?&gt;
</pre>

<p>
This is a simple PHP script demonstrating an interface.
</p>

<pre class="explanation">
interface IInfo {

    public function do_inform();
}
</pre>

<p>
This is an interface <code>IInfo</code>. It has the do_inform()
method signature.
</p>

<pre class="explanation">
class Some implements IInfo {
</pre>

<p>
We use the <code>implements</code> to implement from an
interface. 
</p>

<pre class="explanation">
public function do_inform() {
    echo "This is a Some class\n";
}
</pre>

<p>
The class provides an implementation for the do_inform() method. 
</p>

<p>
The next example shows, how a class can implement multiple
interfaces.
</p>

<pre class="code">
&lt;?php

interface Device {
    public function switch_on();
    public function switch_off();
}

interface Volume {
    public function volume_up();
    public function volume_down();
}

interface Pluggable {
    public function plug_in();
    public function plug_off();
}

class CellPhone implements Device, Volume, Pluggable {

    public function switch_on() { echo "Switching on\n"; }
    public function switch_off() { echo "Switching off\n"; }

    public function volume_up() { echo "Volume up\n"; }
    public function volume_down() { echo "Volume down\n"; }

    public function plug_in() { echo "Plugging in\n"; }
    public function plug_off() { echo "Plugging off\n"; }
}

$o = new CellPhone();
$o->switch_on();
$o->volume_up();
$o->plug_in();

?&gt;
</pre>

<p>
We have a <b>CellPhone</b> class that inherits from three interfaces. 
</p>

<pre class="explanation">
class CellPhone implements Device, Volume, Pluggable {
</pre>

<p>
The class implements all three interfaces, which are divided by a comma.
The CellPhone class must implement all method signatures from all three interfaces. 
</p>

<pre>
$ php interface.php 
Switching on
Volume up
Plugging in
</pre>

<p>
Running the PHP script. 
</p>

<p>
The next example shows how interfaces can extend from multiple other
interfaces. 
</p>

<pre class="code">
&lt;?php

interface IInfo {

    public function do_inform();
}

interface IVersion {

    public function get_version();
}

interface ILog extends IInfo, IVersion {

    public function do_log();
}


class DBConnect implements ILog {

    public function do_inform() {
        echo "This is a DBConnect class\n";
    }

    public function get_version() {
        echo "Version 1.02\n";
    }

    public function do_log() {
        echo "Logging\n";
    }

    public function connect() {
        echo "Connecting to the database\n";
    }
}

$db = new DBConnect();
$db->do_inform();
$db->get_version();
$db->do_log();
$db->connect();

?&gt;
</pre>

<p>
In this PHP script, we define three interfaces. 
Extending interfaces allows us to organize them.
</p>

<pre class="explanation">
interface ILog extends IInfo, IVersion {

    public function do_log();
}
</pre>

<p>
The <b>ILog</b> interface extends other two interfaces.
</p>

<pre class="explanation">
public function do_inform() {
    echo "This is a DBConnect class\n";
}
</pre>

<p>
The DBConnect class implements the do_inform() method. 
This method was inherited by the ILog interface, 
which the class implements. 
</p>

<h2>Polymorphism</h2>

<p>
The polymorphism is the process of using an operator or function in different 
ways for different data input. In practical terms, polymorphism means that if 
class B inherits from class A, it doesn’t have to inherit everything about 
class A; it can do some of the things that class A does differently. (wikipedia)
</p>

<p>
In general, polymorphism is the ability to appear in different forms. 
Technically, it is the ability to redefine methods for derived classes. 
Polymorphism is concerned with the application of specific implementations
to an interface or a more generic base class. 
</p>

<pre class="code">
&lt;?php

abstract class Shape {
    
    private $x = 0;
    private $y = 0;

    public abstract function area();
}

class Rectangle extends Shape {

    function __construct($x, $y) {
        $this->x = $x;
        $this->y = $y;
    }

    function area() {
        return $this->x * $this->y;
    }
}

class Square extends Shape {

    function __construct($x) {
        $this->x = $x;
    }

    function area() {
        return $this->x * $this->x;
    }
}

$shapes = array(
    new Square(5), 
    new Rectangle(12, 4), 
    new Square(8)
);

foreach ($shapes as $shape) {
    echo $shape->area() . "\n";
}

?&gt;
</pre>

<p>
In the above PHP script, we have an abstract Shape class. This class morphs into two 
descendant classes, Rectangle and Square. Both provide their own implementation of
the area() method. Polymorphism brings flexibility and scalability to the OOP systems. 
</p>

<p>
This was the first part of the description of OOP in PHP 5.
</p>


<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 
<br> 


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified February 20, 2010  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

